#include "include/server.h"

// 定义每次调整的线程数量（避免在头文件中定义）
#define NUMBER 2


ThreadPool* threadPoolCreate(int min, int max, int queueSize) {
    ThreadPool* pool = (ThreadPool*)malloc(sizeof(ThreadPool));
    do {
        ERROR_CHECK(pool, NULL, "create pool failed");
        // 工作线程
        pool->threadIDs = (pthread_t*)malloc(sizeof(pthread_t *) * max);
        ERROR_CHECK(pool->threadIDs, NULL, "malloc threadIDs failed");
        memset(pool->threadIDs, 0, sizeof(pthread_t *) * max);
        
        pool->minNum = min;
        pool->maxNum = max;
        pool->busyNum = 0;
        pool->liveNum = min;  // 初始存活线程数等于最小值
        pool->exitNum = 0;

        // 初始化锁和条件变量
        if (pthread_mutex_init(&pool->mutexPool, NULL) != 0 ||
            pthread_mutex_init(&pool->mutexBusy, NULL) != 0 ||
            pthread_cond_init(&pool->notEmpty, NULL) != 0 ||
            pthread_cond_init(&pool->notFull, NULL) != 0) 
        {
            perror("mutex or cond init fail");
            break;
        }

        // 任务队列
        pool->taskQ = (Task*)malloc(sizeof(Task*) * queueSize);
        ERROR_CHECK(pool->taskQ, NULL, "malloc taskQ failed");
        pool->queueCapacity = queueSize;
        pool->queueSize = 0;
        pool->queueRear = 0;
        pool->queueFront = 0;
        // 销毁线程池的标志
        pool->shutdown = 0;

        // 创建管理者线程
        if (pthread_create(&pool->managerID, NULL, manager, pool) != 0) {
            perror("create manager thread failed");
            break;
        }
        
        // 创建工作线程
        for (int i = 0; i < min; i++) {
            if (pthread_create(&pool->threadIDs[i], NULL, worker, pool) != 0) {
                perror("create worker thread failed");
                break;
            }
        }
        return pool;
    } while (0);

    // 错误处理：释放资源
    if (pool && pool->threadIDs) free(pool->threadIDs);
    if (pool && pool->taskQ) free(pool->taskQ);
    if (pool) free(pool);
    return NULL;
}

void threadPoolDestroy(ThreadPool* pool) {
    if (pool == NULL) return;

    // 关闭线程池
    pool->shutdown = 1;
    
    // 等待管理者线程退出
    pthread_join(pool->managerID, NULL);
    
    // 唤醒所有工作线程
    pthread_mutex_lock(&pool->mutexPool);
    pool->exitNum = pool->liveNum;  // 设置所有线程退出
    pthread_cond_broadcast(&pool->notEmpty);
    pthread_mutex_unlock(&pool->mutexPool);
    
    // 等待所有工作线程退出
    for (int i = 0; i < pool->maxNum; i++) {
        if (pool->threadIDs[i] != 0) {
            pthread_join(pool->threadIDs[i], NULL);
        }
    }

    // 释放资源
    if (pool->taskQ) free(pool->taskQ);
    if (pool->threadIDs) free(pool->threadIDs);
    
    pthread_mutex_destroy(&pool->mutexPool);
    pthread_mutex_destroy(&pool->mutexBusy);
    pthread_cond_destroy(&pool->notEmpty);
    pthread_cond_destroy(&pool->notFull);
    
    free(pool);
}

void threadPoolAdd(ThreadPool* pool, void(*func)(void*), void* arg) {
    if (pool == NULL || pool->shutdown) return;
    
    pthread_mutex_lock(&pool->mutexPool);
    
    // 等待队列有空位
    while (pool->queueSize == pool->queueCapacity && !pool->shutdown) {
        pthread_cond_wait(&pool->notFull, &pool->mutexPool);
    }
    
    if (pool->shutdown) {
        pthread_mutex_unlock(&pool->mutexPool);
        return;
    }
    
    // 添加任务
    pool->taskQ[pool->queueRear].function = func;
    pool->taskQ[pool->queueRear].arg = arg;
    pool->queueRear = (pool->queueRear + 1) % pool->queueCapacity;
    pool->queueSize++;
    
    // 通知工作线程
    pthread_cond_signal(&pool->notEmpty);
    pthread_mutex_unlock(&pool->mutexPool);
}

int threadPoolBusyNum(ThreadPool* pool) {
    if (pool == NULL) return 0;
    
    pthread_mutex_lock(&pool->mutexBusy);
    int busyNum = pool->busyNum;
    pthread_mutex_unlock(&pool->mutexBusy);
    return busyNum;
}

int threadPoolLiveNum(ThreadPool* pool) {
    if (pool == NULL) return 0;
    
    pthread_mutex_lock(&pool->mutexPool);
    int liveNum = pool->liveNum;
    pthread_mutex_unlock(&pool->mutexPool);
    return liveNum;
}

void* worker(void* arg) {
    ThreadPool* pool = (ThreadPool*)arg;
    if (pool == NULL) return NULL;
    
    while (1) {
        pthread_mutex_lock(&pool->mutexPool);
        
        // 等待任务或关闭信号
        while (pool->queueSize == 0 && !pool->shutdown) {
            pthread_cond_wait(&pool->notEmpty, &pool->mutexPool);
            
            // 检查是否需要销毁线程
            if (pool->exitNum > 0) {
                pool->exitNum--;
                if (pool->liveNum > pool->minNum) {
                    pool->liveNum--;
                    pthread_mutex_unlock(&pool->mutexPool);
                    threadExit(pool);
                } else {
                    pool->exitNum = 0; // 防止过度销毁
                }
            }
        }
        
        // 检查线程池是否关闭
        if (pool->shutdown && pool->queueSize == 0) {
            pthread_mutex_unlock(&pool->mutexPool);
            threadExit(pool);
        }
        
        // 取出任务
        Task task;
        task.function = pool->taskQ[pool->queueFront].function;
        task.arg = pool->taskQ[pool->queueFront].arg;
        pool->queueFront = (pool->queueFront + 1) % pool->queueCapacity;
        pool->queueSize--;
        
        // 通知生产者有空位
        pthread_cond_signal(&pool->notFull);
        pthread_mutex_unlock(&pool->mutexPool);
        
        // 执行任务前标记忙碌
        pthread_mutex_lock(&pool->mutexBusy);
        pool->busyNum++;
        pthread_mutex_unlock(&pool->mutexBusy);
        
        // 执行任务
        if (task.function && task.arg) {
            task.function(task.arg);
        }
        
        // 任务执行后清除忙碌状态
        pthread_mutex_lock(&pool->mutexBusy);
        pool->busyNum--;
        pthread_mutex_unlock(&pool->mutexBusy);
    }
    return NULL;
}

void* manager(void* arg) {
    ThreadPool* pool = (ThreadPool*)arg;
    if (pool == NULL) return NULL;
    
    while (!pool->shutdown) {
        sleep(3); // 每3秒检测一次
        
        // 获取线程池状态
        pthread_mutex_lock(&pool->mutexPool);
        int queueSize = pool->queueSize;
        int liveNum = pool->liveNum;
        pthread_mutex_unlock(&pool->mutexPool);
        
        pthread_mutex_lock(&pool->mutexBusy);
        int busyNum = pool->busyNum;
        pthread_mutex_unlock(&pool->mutexBusy);
        
        // 动态增加线程 (任务数 > 存活线程数 且 未达上限)
        if (queueSize > liveNum && liveNum < pool->maxNum) {
            pthread_mutex_lock(&pool->mutexPool);
            int counter = 0;
            for (int i = 0; i < pool->maxNum && counter < NUMBER && pool->liveNum < pool->maxNum; i++) {
                if (pool->threadIDs[i] == 0) {
                    if (pthread_create(&pool->threadIDs[i], NULL, worker, pool) == 0) {
                        counter++;
                        pool->liveNum++;
                    }
                }
            }
            pthread_mutex_unlock(&pool->mutexPool);
        }
        
        // 动态减少线程 (忙线程不足存活线程的一半 且 高于最小线程数)
        if (busyNum * 2 < liveNum && liveNum > pool->minNum) {
            pthread_mutex_lock(&pool->mutexPool);
            pool->exitNum = NUMBER; // 每次销毁NUMBER个线程
            pthread_mutex_unlock(&pool->mutexPool);
            
            // 唤醒工作线程让其自行销毁
            for (int i = 0; i < NUMBER; i++) {
                pthread_cond_signal(&pool->notEmpty);
            }
        }
    }
    return NULL;
}

// 线程退出处理
 void threadExit(ThreadPool* pool) {
    if (pool == NULL) return;
    
    pthread_t tid = pthread_self();
    pthread_mutex_lock(&pool->mutexPool);
    for (int i = 0; i < pool->maxNum; i++) {
        if (pool->threadIDs[i] == tid) {
            pool->threadIDs[i] = 0;
            break;
        }
    }
    pthread_mutex_unlock(&pool->mutexPool);
    pthread_exit(NULL);
}

















